﻿package net.wangit.dev.component;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.framework.config.ConsoleSettings;
import net.wangit.jdbc.DB;
import net.wangit.util.Checker;

public class ObjectTreeHelper {

	private static final String LABEL_RULE = "net.wangit.dev.component.ComponentTreeHelper.label.rule";
	private static final String COUNT_NAME = "rowcount";
	private static final String SQL_SUB_UNIT = "select count(*) rowcount from ELEMENT where uid=? and c=?";
	private static final String SQL_ELEMENT_PRIVILEGES = "select count(*) rowcount from ELEMENT where uid=? and au=1";

	public ObjectTreeHelper() {
	}

	public static String getUnitIcon(DB db, String unitId, Row row,
			boolean checkPrivileges) throws Exception {
		int c = row.getInt("c", 1);
		int hasSubUnits;
		if (c == 4 || c == 7)
			hasSubUnits = 0;
		else
			hasSubUnits = hasSubUnits(db, unitId);
		boolean hasPrivileges = false;
		if (checkPrivileges) {
			hasPrivileges = "1".equals(row.get("au"));
			if (!hasPrivileges)
				hasPrivileges = !Checker.isEmpty(row.get("dpid"));
			if (!hasPrivileges)
				hasPrivileges = hasElementPrivileges(db, unitId);
		}
		String accessible = row.get("pp");
		String lock = row.get("l", "0");
		String published = row.get("y", "0");
		StringBuffer icon = new StringBuffer("u");
		icon.append(c).append(hasSubUnits).append(accessible).append(
				hasPrivileges ? "1" : "0").append(lock).append(published)
				.append(".png");
		return icon.toString();
	}

	public static String getLableRule(ActionContext ac) {
		return ActionContextHelper.getRequest2Session(ac,
				"component.labelrule", ObjectTreeHelper.LABEL_RULE,
				ConsoleSettings.instance().getComponentLabelRule());
	}

	private static int hasSubUnits(DB db, String unitId) throws Exception {
		MapList list = db.query(ObjectTreeHelper.SQL_SUB_UNIT, new String[] {
				unitId, Integer.toString(80) }, new int[] { 2, 12 });
		return list.getRow(0).getInt(ObjectTreeHelper.COUNT_NAME, 0) <= 0 ? 0
				: 1;
	}

	private static boolean hasElementPrivileges(DB db, String unitId)
			throws Exception {
		MapList list = db.query(ObjectTreeHelper.SQL_ELEMENT_PRIVILEGES,
				unitId, 2);
		return list.getRow(0).getInt(ObjectTreeHelper.COUNT_NAME, 0) > 0;
	}
}
